const sequelize = require('../../config/db');
const Attr = require('../../models/product/attr.model');
const AttrValue = require('../../models/product/attrValue.model');
const sendResponse = require('../../utils/response');

// 获取某个分类下的属性列表
exports.getAttrInfoList = async (req, res, next) => {
  try{
    const { category1Id, category2Id, category3Id } = req.params;
    if (!category3Id || isNaN(category3Id)) return sendResponse(res, { code: 400, message: '缺少参数' });
    const attrList = await Attr.findAll({
      where: { categoryId: category3Id },
      // 排序
      order: [['id', 'ASC']],
      include: [{ 
        model: AttrValue,
        as: 'attrValueList',
        attributes: ['id', 'valueName', 'attrId', 'flag'],
      }],
      distinct: true, // 确保正确计数主模型
    });
    return sendResponse(res, { message: '获取属性列表成功', data: attrList });
  } catch (error){
    next(error);
  }
}

// 添加或修改属性
exports.saveAttrInfo = async (req, res, next) => {
  try{
    const { id, categoryId, attrName, categoryLevel, attrValueList } = req.body;
    if (!attrName || !categoryId) return sendResponse(res, { code: 400, message: '缺少参数' });

    // 判断id是否存在，如果存在则修改，不存在则添加
    const attr = 
      id ? await Attr.update({ attrName, categoryId, categoryLevel}, { where: { id } }) : 
      await Attr.create({ categoryId, attrName, categoryLevel });

    const newAttr = await Attr.findOne({ 
      where: { id: attr.id || id }
    });

    // 批量创建属性值
    await sequelize.transaction(async (t) => {
      // 删除属性值
      await AttrValue.destroy({ 
        where: { attrId: newAttr.id },
        transaction: t
      });
      // 批量创建
      await AttrValue.bulkCreate(
        attrValueList.map(item => ({
          ...item,
          attrId: newAttr.id // 确保外键赋值
        })),
        { transaction: t }
      );
    });

    return sendResponse(res, { message: id ? '修改属性成功' : '添加属性成功', data: attr });
  }catch(error){
    next(error);
  }
}

// 删除属性
exports.deleteAttr = async (req, res, next) => {
  try{
    const { attrId } = req.params;
    if (!attrId) return sendResponse(res, { code: 400, message: '缺少参数' });

    // 判断属性下是否有属性值
    // const attrValueList = await AttrValue.findAll({ where: { attrId } });
    // if (attrValueList.length > 0) return sendResponse(res, { code: 400, message: '该属性下有属性值，不能删除' });

    // 删除属性，同时删除属性值
    const result = await Attr.destroy({ 
      where: { id: attrId },
      individualHooks: true // 如果需要触发钩子
    });

    if (result === 0) return sendResponse(res, { code: 400, message: '属性不存在' });

    await AttrValue.destroy({ 
      where: { attrId: attrId },
    });
    return sendResponse(res, { message: '删除属性成功' });
  }catch(error){
    next(error);
  }
}
